package com.cj.ai.service.impl;

import com.cj.ai.MpProperties;
import com.cj.ai.domain.WxLogin;
import com.cj.ai.mapper.WxLoginMapper;
import com.cj.ai.service.IWxLoginService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cj.common.constant.CacheConstants;
import com.cj.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cc
 * @since 2024-08-20
 */
@Service
@EnableConfigurationProperties(MpProperties.class)
@Slf4j
public class WxLoginServiceImpl extends ServiceImpl<WxLoginMapper, WxLogin> implements IWxLoginService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    MpProperties mpProperties;
    @Override
    public WxLogin login(String code) {

        Map<String, Object> params = new HashMap<>();
        params.put("appid",mpProperties.getAppid());
        params.put("secret",mpProperties.getSecret());
        params.put("js_code",code);
        WxLogin wxLogin = restTemplate.getForObject(mpProperties.getTokenUrl(), WxLogin.class, params);
        log.info("wxlogin={}",wxLogin);

        if (wxLogin.getErrmsg() == null || ( wxLogin.getOpenid() !=null && wxLogin.getOpenid().length()>0)){
            // 成功
            save(wxLogin);
            // redis存uuid ，， openid是唯一不会变的，不安全
            wxLogin.setSessionKey(UUID.randomUUID().toString());
            //
            save2Redis(wxLogin);
        }

//        // ???这个东西返回给小程序，，小程序不用他，，也不是很安全
//        wxLogin.setSessionKey(null);
        return wxLogin;
    }

    @Autowired
    RedisCache redisCache;
    private void save2Redis(WxLogin wxLogin) {
        redisCache.setCacheObject(CacheConstants.WX_LOGIN_PREFIX+wxLogin.getSessionKey(),wxLogin,60, TimeUnit.MINUTES);
    }
}
